package com.cskaoyan.day01.linkdemo;

/**
 * 成环判断
 * @author stone
 * @date 2022/01/27 14:37
 */
public class LinkedDemo3 {

    public static void main(String[] args) {
        Node node1 = new Node("红");
        Node node2 = new Node("橙");
        Node node3 = new Node("黄");
        Node node4 = new Node("绿");
        Node node5 = new Node("青");
        Node node6 = new Node("蓝");
        Node node7 = new Node("紫");

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;

        node7.next = node3;
        boolean hasCircle = hasCircle(node1);
        System.out.println("成环：" + hasCircle);
    }

    public static boolean hasCircle(Node head) {
        //定义快慢结点
        Node fast = head;
        Node slow = head;
        //遍历条件是啥 → 获得中间结点的遍历条件是一样的
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            //fast和slow初始值都是head，是相等的，先让快慢结点动起来
            if (fast == slow) {
                return true;
            }
        }
        return false;
    }

}
